package top.mccsdl.Acbot.utils;


import top.mccsdl.Acbot.entity.KeyValue;
import top.mccsdl.Acbot.entity.user.Plugins;
import top.mccsdl.Acbot.entity.user.UserInfo;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class PictureUtil {

    public final static PictureUtil pictureUtil = new PictureUtil();

    private PictureUtil() {

    }

    public static PictureUtil getInstance() {
        return pictureUtil;
    }

    public static void main(String[] args) throws MalformedURLException {
        List<Plugins> plugins = new ArrayList<>();
        Plugins e = new Plugins();
        e.setMoney("1");
        e.setNick("233");
        e.setQq("123");
        e.setPluginName("222222");
        e.setStatus("1");
        plugins.add(e);
        PictureUtil.createImages(plugins, "img\\", "show.png");
        File file = new File("img\\show.png");
        URL url = file.toURI().toURL();
        System.out.println(url);
    }

    /**
     * 商店图片
     *
     * @param list     插件列表
     * @param filePath
     * @param fileName
     */
    public static void createImages(List<Plugins> list, String filePath, String fileName) {
        try {
            String[][] tableData2 = new String[list.size() + 1][5];
            tableData2[0][0] = "插件名称";
            tableData2[0][1] = "中文名称";
            tableData2[0][2] = "售价(R)";
            tableData2[0][3] = "状态";
            tableData2[0][4] = "作者QQ";
            int i = 1;
            for (Plugins p : list) {
                tableData2[i][0] = p.getPluginName();
                tableData2[i][1] = p.getNick();
                tableData2[i][2] = p.getMoney();
                tableData2[i][3] = p.getStatus();
                tableData2[i][4] = p.getQq();
                i++;
            }
            myGraphicsGeneration(tableData2, "AcCore v2.0", filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户个人信息
     *
     * @param list     拥有的插件
     * @param userInfo 个人信息
     * @param filePath
     * @param fileName
     */
    public static void createImagesUserInfo(List<KeyValue> list, UserInfo userInfo, String filePath, String fileName) {
        try {
            String[][] tableData2 = new String[list.size() + 1][2];
            tableData2[0][0] = "插 件 名 称";
            tableData2[0][1] = "脱敏授权码(完整私聊机器人查看)";
            int i = 1;
            for (KeyValue p : list) {
                tableData2[i][0] = p.getK();
                tableData2[i][1] = p.getV();
                i++;
            }
            myGraphicsGenerationUserInfo(userInfo, tableData2, filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成用户信息(脱敏授权)图片
     *
     * @param userInfo
     * @param cellsValue
     * @param path
     * @param fileName
     */
    public static void myGraphicsGenerationUserInfo(UserInfo userInfo, String cellsValue[][], String path, String fileName) {
        // 字体大小
        int fontTitileSize = 40;
        // 横线的行数
        int totalrow = cellsValue.length + 1;
        // 竖线的行数
        int totalcol = 0;
        if (cellsValue[0] != null) {
            totalcol = cellsValue[0].length;
        }
        // 图片宽度
        int imageWidth = 1210;
        // 行高
        int rowheight = 60;
        // 图片高度
        int imageHeight = totalrow * rowheight + 200;
        // 起始高度
        int startHeight = 130;
        // 起始宽度
        int startWidth = 10;
        // 单元格宽度
        int colwidth = (int) ((imageWidth - 20) / totalcol);
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.darkGray);//图片背景颜色
        graphics.fillRect(0, 0, imageWidth, imageHeight);
        graphics.setColor(new Color(57, 61, 61));

        //画横线
        for (int j = 0; j < totalrow; j++) {
            graphics.setColor(Color.WHITE);
            graphics.drawLine(startWidth,
                    startHeight + (j + 1) * rowheight,
                    startWidth + colwidth * totalcol,
                    startHeight + (j + 1) * rowheight);
        }
        //画竖线
        for (int k = 0; k < totalcol + 1; k++) {
            graphics.setColor(Color.WHITE);
            graphics.drawLine(startWidth + k * colwidth,
                    startHeight + rowheight,
                    startWidth + k * colwidth,
                    startHeight + rowheight * totalrow);
        }

        //设置字体
        Font font = new Font("微软雅黑", Font.BOLD, fontTitileSize);
        graphics.setFont(font);
        graphics.setColor(new Color(243, 227, 202));

        //写标题
        String title02 = "AcCore积分：" + userInfo.getAcb();
        graphics.drawString(title02, startWidth, startHeight + rowheight - 10);


        Font fonttile = new Font("微软雅黑", Font.BOLD, 50);
        graphics.setFont(fonttile);

        graphics.setColor(new Color(62, 170, 255));
        //写标题
        String title03 = "用 户 信 息";
        graphics.drawString(title03, 740, 70);

        graphics.setColor(new Color(145, 207, 253));
        //写标题
        String title04 = userInfo.getName() + " [LV: " + userInfo.getLv() + "]";
        graphics.drawString(title04, 740, 150);
        // 下载用户头像HTTPS图片并绘制到主图片上
        try {
            String avatar = userInfo.getAvatar();
            System.out.println("用户头像地址:"+avatar);
            BufferedImage overlayImage = downloadImage(avatar);
            if (overlayImage != null) {
                // 设定要绘制的位置（例如：x=100, y=100）
                int x = 570;
                int y = 50;

                // 绘制图片
                graphics.drawImage(overlayImage, x, y, null);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //写入内容
        for (int n = 0; n < cellsValue.length; n++) {
            for (int h = 0; h < cellsValue[n].length; h++) {
                font = new Font("微软雅黑", Font.PLAIN, fontTitileSize);
                graphics.setFont(font);
                if (n == 0) {
                    graphics.setColor(Color.ORANGE);
                } else {
                    graphics.setColor(Color.WHITE);
                }
                if (h > 0) {
                    if (cellsValue[n][h].equals(cellsValue[n][h - 1])) {

                    } else {
                        graphics.drawString(cellsValue[n][h], startWidth + colwidth * h + 5, startHeight + rowheight * (n + 2) - 10);
                    }
                } else {
                    graphics.drawString(cellsValue[n][h], startWidth + colwidth * h + 5, startHeight + rowheight * (n + 2) - 10);

                }


            }
        }
        // 保存图片
        createImage(image, path, fileName);
    }

    public static void myGraphicsGeneration(String cellsValue[][], String contractBh, String path, String fileName) {
        // 字体大小
        int fontTitileSize = 40;
        // 横线的行数
        int totalrow = cellsValue.length + 1;
        // 竖线的行数
        int totalcol = 0;
        if (cellsValue[0] != null) {
            totalcol = cellsValue[0].length;
        }
        // 图片宽度
        int imageWidth = 1792;
        // 行高
        int rowheight = 60;
        // 图片高度
        int imageHeight = totalrow * rowheight + 100;
        // 起始高度
        int startHeight = 50;
        // 起始宽度
        int startWidth = 10;
        // 单元格宽度
        int colwidth = (int) ((imageWidth - 20) / totalcol);
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.darkGray);//图片背景颜色
        graphics.fillRect(0, 0, imageWidth, imageHeight);
        graphics.setColor(new Color(70, 89, 89));

        //画横线
        for (int j = 0; j < totalrow; j++) {
            graphics.setColor(Color.WHITE);
            graphics.drawLine(startWidth,
                    startHeight + (j + 1) * rowheight,
                    startWidth + colwidth * totalcol,
                    startHeight + (j + 1) * rowheight);
        }
        //画竖线
        for (int k = 0; k < totalcol + 1; k++) {
            graphics.setColor(Color.WHITE);
            graphics.drawLine(startWidth + k * colwidth,
                    startHeight + rowheight,
                    startWidth + k * colwidth,
                    startHeight + rowheight * totalrow);
        }

        graphics.setColor(Color.WHITE);
        //设置字体
        Font font = new Font("微软雅黑", Font.BOLD, fontTitileSize);
        graphics.setFont(font);

        //写标题
        String title02 = "版本：" + contractBh;
        graphics.drawString(title02, startWidth, startHeight + rowheight - 10);


        Font fonttile = new Font("微软雅黑", Font.BOLD, 50);
        graphics.setFont(fonttile);

        graphics.setColor(Color.WHITE);
        //写标题
        String title03 = "插 件 商 城";
        graphics.drawString(title03, 800, 40);

        graphics.setColor(Color.CYAN);
        //写标题
        String title04 = "欢迎各位老板前来咨询";
        graphics.drawString(title04, 690, 88);
        //写入内容
        for (int n = 0; n < cellsValue.length; n++) {
            for (int h = 0; h < cellsValue[n].length; h++) {
                font = new Font("微软雅黑", Font.PLAIN, fontTitileSize);
                graphics.setFont(font);
                if (n == 0) {
                    graphics.setColor(Color.ORANGE);
                } else {
                    if ((n - 1) % 2 == 0) {
                        graphics.setColor(new Color(108, 180, 255)); // 偶数行（从第2行开始计算，所以是 currentRow-1）为黑色
                    } else {
                        graphics.setColor(new Color(124, 139, 255)); // 奇数行为白色
                    }
                    String s = cellsValue[n][3];
                    switch (s) {
                        case "免费领取" -> graphics.setColor(new Color(58, 124, 82));
                        case "停售" -> graphics.setColor(new Color(87, 86, 86));
                        case "开发中" -> graphics.setColor(new Color(175, 175, 175));
                    }
                }
                if (h > 0) {
                    if (cellsValue[n][h].equals(cellsValue[n][h - 1])) {

                    } else {
                        graphics.drawString(cellsValue[n][h], startWidth + colwidth * h + 5, startHeight + rowheight * (n + 2) - 10);
                    }
                } else {
                    graphics.drawString(cellsValue[n][h], startWidth + colwidth * h + 5, startHeight + rowheight * (n + 2) - 10);

                }


            }
        }
        // 保存图片
        createImage(image, path, fileName);
    }

    /**
     * 将图片保存到指定位置
     *
     * @param image        缓冲文件类
     * @param fileLocation 文件位置
     */
    public static void createImage(BufferedImage image, String fileLocation, String fileName) {
        try {
            File file = new File(fileLocation);
            if (!file.exists()) {
                file.mkdir();
            }
            FileOutputStream fos = new FileOutputStream(fileLocation + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            ImageIO.write(image, "png", fos);
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 下载HTTPS图片的方法
    private static BufferedImage downloadImage(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try (InputStream inputStream = connection.getInputStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            byte[] imageBytes = outputStream.toByteArray();
            try (InputStream imageInputStream = new ByteArrayInputStream(imageBytes)) {

                BufferedImage read = ImageIO.read(imageInputStream);
                return resizeImage(read, 100, 100);
            }
        }
    }

    // 缩放图片的方法
    private static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, originalImage.getType());
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
        g.dispose();

        Image scaledImage = resizedImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
        BufferedImage highQualityImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D highQualityG = highQualityImage.createGraphics();
        highQualityG.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        highQualityG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        highQualityG.drawImage(scaledImage, 0, 0, null);
        highQualityG.dispose();


        return highQualityImage; // 或者返回 scaledImage（如果使用AffineTransform方法）
    }
}

